package com.luckycoder.controller;

import com.luckycoder.entity.User;
import com.luckycoder.entity.UserList;
import com.luckycoder.entity.UserMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/*
  [desc] 数据绑定，基本数据类型 HandleAdaptor 会将参数自动转换为 形参，然后使用@ResponseBody 即可返回数据给页面
  [注意] 集合绑定，需要用实体类封装，jsp中name属性需要与集合名字一致，细节看 bindList 与 bindMap
  [JSON] JSON 格式绑定，比较麻烦，SpringBoot 处理更优雅，此处略
 */

@Controller
@RequestMapping("/data")
public class DataBindHandle {

    /*[url] http://localhost:8080/data/baseType?id=1 */
    @RequestMapping("/baseType")
    @ResponseBody
    public String baseType(int id) {
        return id + "";
    }

    /*[url] http://localhost:8080/data/packageType?id=1 */
    @RequestMapping("/packageType")
    @ResponseBody
    public String packageType(Integer id) {
        return id + "";
    }

    /*[url] http://localhost:8080/data/packageType1?number=1 */
    @RequestMapping("/packageType1")
    @ResponseBody
    public String packageType1(@RequestParam(value = "number", required = true) Integer id) {
        return id + "";
    }

    /*[后台返回中文乱码] 在springmvc.xml 里面 配置消息转换器 */
    @RequestMapping(value="/bindList",method = RequestMethod.POST)
    @ResponseBody
    public String bindList(UserList userList) {
        StringBuffer str = new StringBuffer();
        for (User user : userList.getUsers()) {
            str.append(user);
        }
        System.out.println(str.toString()+"======");
        return str.toString();
    }
    /*[后台返回中文乱码] 在springmvc.xml 里面 配置消息转换器 */
    @RequestMapping(value="/bindMap",method = RequestMethod.POST)
    @ResponseBody
    public String bindMap(UserMap userMap) {
        StringBuffer str = new StringBuffer();
        for (Map.Entry<String,User> entry:userMap.getUsers().entrySet()){
            str.append(entry.getValue());
        }
        System.out.println(str.toString()+"======");
        return str.toString();
    }
}










